package libs.yzx.zaza.util;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

import libs.yzx.zaza.R;

public class GunLunView extends FrameLayout{

    public GunLunView(Context context) {
        super(context); init();
    }
    public GunLunView(Context context, AttributeSet attrs) {
        super(context, attrs); init();
    }
    public GunLunView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr); init();
    }


    private final int ITEM_HEIGHT = dp2px(35);
    private boolean hasStateReady = false;
    private ListView listview;
    private MyAdapter adapter;
    private List<String> list;
    private int textColor = Color.rgb(0x77,0x77,0x77), lineColor = Color.BLACK;
    private boolean canDoOnIDEL = false;
    private ValueAnimator anim;

    private void init(){
        LayoutInflater.from(getContext()).inflate(R.layout.view_gunlun, this, true);
        listview = (ListView) findViewById(R.id.listview);
        listview.setVerticalScrollBarEnabled(false);
        listview.setOverScrollMode(View.OVER_SCROLL_NEVER);
        post(new Runnable() {
            public void run() {
                hasStateReady = true;
                {/* 设置中间LineLayout的高度和颜色 */
                    View ll = findViewById(R.id.lineLayout);
                    ll.getLayoutParams().height = ITEM_HEIGHT;
                    ll.requestLayout();
                    setLineColor();
                }
                {/* 添加ListView的header和footer */
                    View header = new View(getContext());
                    View footer = new View(getContext());
                    AbsListView.LayoutParams lp = new ListView.LayoutParams(-1, ITEM_HEIGHT);
                    header.setLayoutParams(lp);
                    footer.setLayoutParams(lp);
                    listview.addHeaderView(header,null,false);
                    listview.addFooterView(footer,null,false);
                }
                {/* 设置ListView的滚动事件,校准选择的item位置 */
                    listview.setOnScrollListener(new AbsListView.OnScrollListener() {
                        public void onScrollStateChanged(AbsListView view, int scrollState) {
                            if(scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                                canDoOnIDEL = true;
                                cancelAnim();
                            } else if(canDoOnIDEL&&scrollState==SCROLL_STATE_IDLE){
                                canDoOnIDEL = false;
                                int targetPosition = getCurrentPositionOfDataList();
                                int hideHeight = getFirstVisibleItemViewHideHeight();
                                int offset;
                                if(hideHeight<ITEM_HEIGHT/2){
                                    offset = -hideHeight;
                                }else
                                    offset = ITEM_HEIGHT - hideHeight;
                                smoothScrollListView(targetPosition, offset);
                            }
                        }
                        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                        }
                    });
                }
            }
        });
    }

    /* 利用setSelectionFromTop(position,offset)这个方法实现滚动,不断改变offset的值 */
    private void smoothScrollListView(final int targetPosition,int offset){
        if(offset == 0) return ;
        anim = ValueAnimator.ofInt(offset, 0);
        anim.setDuration(150);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                int current = (int) animation.getAnimatedValue();
                listview.setSelectionFromTop(targetPosition,current);
            }
        });
        anim.addListener(new Animator.AnimatorListener() {
            public void onAnimationStart(Animator animation) {
            }
            public void onAnimationEnd(Animator animation) {
                cancelAnim();
            }
            public void onAnimationCancel(Animator animation) {
            }
            public void onAnimationRepeat(Animator animation) {
            }
        });
        anim.start();
    }
    private void cancelAnim(){
        if(anim != null){
            anim.cancel();
            anim = null;
        }
    }
    private int getFirstVisibleItemViewHideHeight(){
        View child = listview.getChildAt(0);
        return -child.getTop();
    }
    private int getCurrentPositionOfDataList(){
        int firstItemHideHeight = getFirstVisibleItemViewHideHeight();
        int firstVisiblePosition = listview.getFirstVisiblePosition();
        if(firstItemHideHeight>ITEM_HEIGHT/2){
            return firstVisiblePosition  + 1;
        }else{
            return firstVisiblePosition;
        }
    }



    /** 获取选中项 */
    public String getSelected(){
        return list.get(getCurrentPositionOfDataList());
    }

    /** 设置选中项 */
    public void setSelected(final String s){
        Runnable run = new Runnable(){
            public void run() {
                int position = -1;
                for (int i = 0; i < list.size(); i++)
                    if(s.equals(list.get(i))){
                        position = i;
                        break;
                    }
                if(position == -1)
                    return ;
                listview.setSelection(position);
            }
        };
        if(hasStateReady) run.run();
        else post(run);
    }

    /** 设置文字颜色和line的颜色 */
    public void setUI(int textColor,int lineColor){
        this.textColor = textColor;
        this.lineColor = lineColor;
        setLineColor();
        if(adapter !=null) adapter.notifyDataSetChanged();
    }

    /**  设置数据  */
    public void setList(List<String> list){
        if(list==null || list.isEmpty()) throw new IllegalStateException("list can not be empty");
        this.list = list;
        Runnable setAdapterRun = new Runnable(){
            public void run() {
                {/* 设置ListView的高度为三倍item */
                    ViewGroup.LayoutParams lp = listview.getLayoutParams();
                    if(lp.height != ITEM_HEIGHT * 3){
                        lp.height = ITEM_HEIGHT * 3;
                        listview.setLayoutParams(lp);
                    }
                }
                listview.setAdapter(adapter = new MyAdapter());
            }
        };
        if(hasStateReady) setAdapterRun.run();
        else post(setAdapterRun);
    }



    private void setLineColor(){
        findViewById(R.id.line1).setBackgroundColor(lineColor);
        findViewById(R.id.line2).setBackgroundColor(lineColor);
    }

    private class MyAdapter extends BaseAdapter{
        public int getCount() {
            return list.size();
        }
        public Object getItem(int position) {
            return list.get(position);
        }
        public long getItemId(int position) {
            return position;
        }
        /* 主要设置item的高度和一些显示属性*/
        private void makeItem(TextView tv){
            tv.setGravity(Gravity.CENTER);
            tv.setSingleLine(true);
            tv.setEllipsize(TextUtils.TruncateAt.MIDDLE);
            tv.setPadding(dp2px(8),0,dp2px(8),0);
            ViewGroup.LayoutParams lp = tv.getLayoutParams();
            if(lp == null) lp = new ViewGroup.LayoutParams(-1,-1);
            lp.width = -1; lp.height = ITEM_HEIGHT;
            tv.setLayoutParams(lp);
        }
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = new TextView(getContext());
                makeItem((TextView) convertView);
            }
            ((TextView)convertView).setText((String)getItem(position));
            ((TextView)convertView).setTextColor(textColor);
            return convertView;
        }
    }

    private int dp2px(int dp){
        return (int) (getResources().getDisplayMetrics().density*dp+0.5);
    }
}
